package com.blog.personalblog.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;

@ControllerAdvice
@Slf4j
public class ExceptionResolver {
    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public String handleOtherExceptions(final Exception ex) {
        if (ex instanceof MethodArgumentNotValidException) {
            // 入参校验错误
            StringBuilder msg = new StringBuilder();
            MethodArgumentNotValidException mex = (MethodArgumentNotValidException) ex;
            BindingResult bindingResult = mex.getBindingResult();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            allErrors.forEach(objectError -> {
                FieldError fieldError = (FieldError) objectError;
                String oneMsg = fieldError.getDefaultMessage();
                msg.append(oneMsg);
                msg.append(";");
            });
            return msg.toString();
        }
        if (ex instanceof ConstraintViolationException e){
            StringBuilder msg = new StringBuilder();
            Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
            for (ConstraintViolation<?> violation : violations) {
                msg.append(violation.getMessage());
            }
            return msg.toString();
        }
        return ex.getMessage();
    }
}
